#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: user.py
@contact: zwb15083976291@163.com
@time: 2021/10/14
"""
import traceback

from django.conf import settings
from django.utils.decorators import method_decorator
from rest_framework.views import APIView

from admin.mixins import AdminLoginMixin
from admin.serializers.user import AdminLoginSerializer, AdminTokenSerializer, AdminSerializer
from common.models import BlogUser
from utils.aliyun_upload import AliUploadToken
from utils.redis_clients import RedisClient
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.token import TokenGenerator
from utils.user_authentication import allow_admin_user
from utils.views import BaseGenericAPIView

import logging

logger = logging.getLogger("default")


class AdminLoginView(AdminLoginMixin, BaseGenericAPIView):
    diff_methods_serializer_class = dict(post=AdminLoginSerializer)
    diff_methods_request_params = dict(post=dict(required=["username", "password"]))

    def post(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        return CommonResponse(message="登录成功", data=self.generate_token(self.serializer.context["admin"]))


@method_decorator(allow_admin_user, name='dispatch')
class AdminInfoView(APIView):

    def get(self, request):
        ret, data = TokenGenerator(secret_key=getattr(settings, "SECRET_KEY"),
                                   salt=getattr(settings, "TOKEN_SALT")).decrypt_token(
            request.META["HTTP_AUTHORIZATION"])
        if not ret:
            return CommonResponse(
                CommonAPIResponseStatus.TOKEN_EXPIRES if data[-1] else CommonAPIResponseStatus.TOKEN_ERROR,
                message=data[0])
        user = BlogUser.objects.filter(username=data['username'], id=data['id']).first()
        return CommonResponse(data=dict(id=user.id, name=user.username, avatar=user.user_image_url))


@method_decorator(allow_admin_user, name='dispatch')
class AdminLogoutView(AdminLoginMixin, APIView):
    def post(self, request):
        if self.login_out():
            return CommonResponse()
        else:
            return CommonResponse(CommonAPIResponseStatus.SERVICE_UNAVAILABLE)


@method_decorator(allow_admin_user, name='dispatch')
class ImageUploadView(APIView):

    def get(self, request):
        upload_type = request.GET.get("upload_type")
        if not upload_type or (upload_type not in ["image", "music"]):
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST)
        object_dir = getattr(settings, "ALI_BUCKET_IMAGE_DIR") if upload_type == "image" else getattr(settings,
                                                                                                      "ALI_BUCKET_MUSIC_DIR")
        return CommonResponse(data=dict(token=AliUploadToken(object_dir).get_upload_image_token()))
